<?php
/**
 * SESSION缓存至Memcached操作类库
 * @copyright Copyright&copy; 2015, 广州六象元一网络科技有限公司
 * @author 王海龙 $
 * @version  $Id: classSessionToMemcached.php, v 1.0, 2015-01-01 王海龙 $
 */

if (!defined('EGGMS'))
{
    die('非法进入');
}

class classSessionToMemcached
{

    public $maxLifeTime  = 3600; // SESSION 最大生存时间
    public $sessionName   = '';
    public $sessionId     = '';

    public $sessionExpiry = '';
    public $sessionMd5    = '';

    public $sessionCookiePath   = '/';
    public $sessionCookieDomain = '';
    public $sessionCookieSecure = false;

    public $_ip   = '';
    public $_time = 0;

    public function __construct($sessionName = 'EGGMS', $maxLifeTime = 3600)
    {
        $this->classSessionToMemcached($sessionName, $maxLifeTime);
    }

    public function classSessionToMemcached($sessionName = 'EGGMS', $maxLifeTime = 3600)
    {
        $GLOBALS['_SESSION'] = array();

        $this->sessionCookiePath = '/';
        $this->sessionCookieDomain = '';
        $this->sessionCookieSecure = false;

        $this->sessionName       = $sessionName;
        $this->_ip = realIp();
        $this->maxLifeTime = $maxLifeTime;

        if (!empty($_COOKIE[$this->sessionName]))
        {
            $this->sessionId = $_COOKIE[$this->sessionName];
        }

        if ($this->sessionId)
        {
            $tmpSessionId = substr($this->sessionId, 0, 32);
            if ($this->genSessionKey($tmpSessionId) == substr($this->sessionId, 32))
            {
                $this->sessionId = $tmpSessionId;
            }
            else
            {
                $this->sessionId = '';
            }
        }

        $this->_time = time();

        if ($this->sessionId)
        {
            $this->loadSession();
        }
        else
        {
            $this->genSessionId();

            setcookie($this->sessionName, $this->sessionId . $this->genSessionKey($this->sessionId), 0, $this->sessionCookiePath, $this->sessionCookieDomain, $this->sessionCookieSecure);
        }

        register_shutdown_function(array(&$this, 'closeSession'));
    }
    /* 生成sessionId */
    public function genSessionId()
    {
        $this->sessionId = md5(uniqid(mt_rand(), true));

        return $this->insertSession();
    }
    /* 系列化sessionId */
    public function genSessionKey($sessionId)
    {
        static $ip = '';

        if ($ip == '')
        {
            $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));
        }

        return sprintf('%08x', crc32(ROOT_PATH . $ip . $sessionId));
    }
    /* 插入新session数据 */
    public function insertSession()
    {
        $GLOBALS['mem']->set($this->sessionName . '_session_' . $this->sessionId, array('realIp' => $this->_ip), $this->_time + $this->maxLifeTime);
    }
    /* 读取session数据 */
    public function loadSession()
    {
        $session = $GLOBALS['mem']->get($this->sessionName . '_session_' . $this->sessionId);
        if (empty($session))
        {
            $this->insertSession();

            $this->sessionExpiry = 0;
            $this->sessionMd5    = '40cd750bba9870f18aada2478b24840a';
            $GLOBALS['_SESSION']  = array();
        }
        else
        {
            $this->sessionMd5    = md5(serialize($session));
            $GLOBALS['_SESSION']  = $session;
        }
    }
    /* 更新session数据 */
    public function updateSession()
    {
        $data        = $GLOBALS['_SESSION'];
        $data['realIp'] = $this->_ip;
        $this->_time = time();

        if ($this->sessionMd5 == md5(serialize($data)))
        {
            return true;
        }
        $GLOBALS['mem']->set($this->sessionName . '_session_' . $this->sessionId, $data, $this->_time + $this->maxLifeTime);
    }
    /* 关闭session */
    public function closeSession()
    {
        $this->updateSession();

        return true;
    }
    /* 获取sessionId */
    public function getSessionId()
    {
        return $this->sessionId;
    }
    /* 获取用户量 */
    public function getUserCount()
    {
        $allKey = memGetAllKeys();
        foreach ($allKey as $key => $value) {
            $prefix = explode('_', $explode);
            if($prefix[0] == $this->sessionName && $prefix[1] == 'session'){
                $count[] = $value;
            }
        }
        return count($count);
    }
}
